package com.iterator.service.wechat.lc;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iterator.bean.web.pojo.zql.Topic;
import com.iterator.bean.web.pojo.zql.TopicExample;
import com.iterator.bean.wechat.lc.TopicListItem;
import com.iterator.bean.wechat.lc.WxTopicDetailVo;
import com.iterator.mapper.web.promotionMapper.TopicMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WxTopicServiceImpl implements WxTopicService {
    @Autowired
    TopicMapper topicMapper;
    @Override
    public Map<String, Object> getList(Integer page, Integer size) {
        PageHelper.startPage(page,size);
        TopicExample topicExample = new TopicExample();
        TopicExample.Criteria criteria = topicExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        List<Topic> topics = topicMapper.selectByExampleWithBLOBs(topicExample);
        PageInfo<Topic> pageInfo = new PageInfo<>(topics);
        long total = pageInfo.getTotal();
        List<TopicListItem> items = new ArrayList<>();
        for (Topic topic : topics) {
            items.add(new TopicListItem(topic.getId(),
                    topic.getTitle(),
                    topic.getSubtitle(),
                    topic.getPrice(),
                    topic.getReadCount(),
                    topic.getPicUrl()
            ));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("count",total);
        map.put("data",items);
        return map;
    }

    @Override
    public WxTopicDetailVo getDetail(Integer id) {
        TopicExample topicExample = new TopicExample();
        topicExample.createCriteria().andDeletedEqualTo(false).andIdEqualTo(id);
        List<Topic> topics = topicMapper.selectByExampleWithBLOBs(topicExample);
        Topic topic = topics.get(0);

        WxTopicDetailVo detailVo = new WxTopicDetailVo();
        detailVo.setTopic(topic);
        detailVo.setGoods(topic.getGoods());
        return detailVo;
    }

    @Override
    public List<Topic> getRelated(Integer id) {
        TopicExample topicExample = new TopicExample();
        TopicExample.Criteria criteria = topicExample.createCriteria();
        topicExample.setOrderByClause("rand() limit 0,4");
        List<Topic> topics = topicMapper.selectByExampleWithBLOBs(topicExample);
        return topics;
    }
}
